'''
Created on 19/03/2010

@author: eh01
'''
from optparse import OptionParser
from datastore.resource import Resource
from datastore.database import DataStore, NotFoundException
import os
import sys

if __name__ == '__main__':
    parser = OptionParser(usage=u"%s [<options>]" % sys.argv[0])
    parser.add_option("--new", dest=u"new_resource", action="store_true", default=False, help=u"Is the resource a new resource (i.e. it does not exist already in the datastore?")
    parser.add_option("--pathrs", dest=u"pathrs", action="store", type="string", help=u"Path to the resource.")
    parser.add_option("--id", dest=u"resource_existing_id", type="int", help=u"Id of the existing resource you want to update.")
    parser.add_option("--pathds", dest=u"pathds", action="store", type="string", help=u"Path to the datastore to update.")
    (options, args) = parser.parse_args()
    options.script = os.path.split(sys.argv[0])[1]
    
    path_to_resource = options.pathrs
    os.path.split(path_to_resource)
    content_of_resource_as_string = open(path_to_resource, 'r').read()
    res = Resource()
    ds = DataStore(options.pathds)
    res.deserialise(content_of_resource_as_string)
    if options.new_resource:
        ds.put([res])
        print '''New resource added. Resource id is {0}'''.format(res.get_id())
    else:
        if options.resource_existing_id:
            try:
                ds.gets([options.resource_existing_id])
            except NotFoundException:
                print '''Failed to find existing resource with id {0}'''.format(options.resource_existing_id)
                sys.exit()
            res.set_id(options.resource_existing_id)
            ds.put([res])
            print '''Existing resource with id {0} updated'''.format(res.get_id())
        else:
            ress = ds.find(res.get_all_metadata())
            if len(ress) == 1:
                res.set_id(ress[0].get_id())
                ds.put([res])
                print '''Existing resource with id {0} updated'''.format(res.get_id())
            else:
                print '''Could not find the existing resource to update based on metadata. If you have updated
                        the resource's metdata then it is not possible to find the exising one'''